﻿// ****************************************************************************
// Product Name: TestViewer.exe
// Description:  A very basic demonstration of the controls.
// ****************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific
// language governing rights and
// limitations under the License.
//
// The Initial Developer of this Original Code is Ted Dunsford. Created during
// refactoring 2010.
// ****************************************************************************
using System;
using System.Diagnostics;
using System.Windows.Forms;
using NAttrArgs;
using System.IO;
using System.Deployment.Application;

namespace MapWindow
{
    internal class Program
    {
        // http://www.codeproject.com/Articles/313016/A-Csharp-NET-Attributes-Based-Command-Line-Argumen
        [NArg(IsOptional = true)]
        public bool DeletePackages { get; set; }

        /// <summary>
        /// Gets or sets the project file.
        /// </summary>
        /// <value>
        /// The project file. (expected as the first parameter)
        /// </value>
        [NArg()]
        public string ProjectFile { get; set; }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        [DebuggerNonUserCode]
        private static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            new Program().Run(GetClickOnceArguments() ?? args);
        }

        private static string GetExecutableName()
        {
            return Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetCallingAssembly().Location);
        }

        /// <summary>
        /// Gets the arguments either from the command line or URI in case of a ClickOnce version.
        /// </summary>
        /// <param name="args">The command linke arguments (returned if app is not ClickOnce).</param>
        /// <returns></returns>
        private static string[] GetClickOnceArguments()
        {
            if (ApplicationDeployment.IsNetworkDeployed &&
                ApplicationDeployment.CurrentDeployment.ActivationUri != null)
            {
                string query = Uri.UnescapeDataString(
                    ApplicationDeployment.CurrentDeployment.ActivationUri.Query);
                if (!string.IsNullOrEmpty(query) && query.StartsWith("?"))
                {
                    string[] arguments = query.Substring(1).Split(' ');
                    return arguments;
                }
            }
            return null;
        }

        private void Run(string[] args)
        {
            try
            {
                new ArgParser<Program>(GetExecutableName()).Parse(this, args);
            }
            catch (NArgException ex)
            {
                // This message is usually a usage statement.
                WriteMessage(ex.Message);
            }

            if (DeletePackages)
            {
                DotSpatial.Controls.Extensions.PackageManager.TryDeleteAllPackages();
            }

            MainForm form = new MainForm();

            if (!String.IsNullOrWhiteSpace(ProjectFile))
            {
                form.appManager.SerializationManager.OpenProject(ProjectFile);
            }

            Application.Run(form);
        }

        private static void WriteMessage(string message)
        {
            // Command line given, display console
            if (AttachConsole(-1))
            {
                // In most cases, when our windows forms application is executed from the command line it wouldn't be able to
                // write out to the console that created it. AttachConsole attempts to to capture the parent command window
                // if there is one.
                Console.WriteLine(message);
            }
        }

        /// <summary>
        /// Attaches the console.
        /// </summary>
        /// <param name="pid">The pid (-1 to attach to a parent process console).</param>
        /// <returns></returns>
        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        private static extern bool AttachConsole(int pid);
    }
}